<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加部门</el-button
          >
        </el-col>
      </el-row>
      <!-- 树形部门列表 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        show-index
        border
        :expand-type="false"
      >
        <template slot="sign" slot-scope="scope">
          <el-tag
            :type="scope.row.type == 1 ? 'primary' : 'success'"
            disable-transitions
            >{{ scope.row.name }}</el-tag
          >
        </template>
        <template slot="opt" slot-scope="scope">
          <!-- 修改按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeDepartById(scope.row.id)"
          ></el-button>
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 修改部门的对话框 -->
    <el-dialog
      title="修改部门"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="FormRules"
        ref="editFormRef"
        label-width="85px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDepartment">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加部门的对话框 -->
    <el-dialog
      title="添加部门"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="FormRules"
        ref="addFormRef"
        label-width="85px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="等级分类">
            <el-cascader
              v-model="selectedCateKeys"
              :options="cateList"
              :props="{ checkStrictly: true }"
              @change="handlechange"
              clearable>
            </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDepartment">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getDepartment,
  addDepartment,
  addDepartments,
  removeDepartment,
  getDepartmentItem,
  editDepartmentItem,
  getDepartmentType,
  getTreeDepartment,
} from '@/api/department'
export default {
  data() {
    return {
      prop: {
        label: 'name',
        children: 'children',
        checkStrictly: true,
        value: 'id',
      },
      columns: [
        {
          label: '部门名称',
          prop: 'name',
        },
        {
          label: '标签',
          type: 'template',
          template: 'sign',
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt',
        },
      ],
      cateList: [],
      departmentTypeOptions: [],
      total: 0,
      selectedCateKeys:[],
      queryInfo:{
        pagesize:5,
        pagenum:1
      },
      // 添加部门的表单数据
      addForm: {
        name: '',
        level:1,
      },
      editForm: {
        name: '',
        level:1,
      },
      // 添加、修改表单的验证规则对象
      FormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '部门名的长度在2~10个字符之间',
            trigger: 'blur',
          },
        ],
        type: [
          { required: true, message: '请选择部门类型', trigger: 'change' },
        ],
      },
    }
  },
  created() {
    // this.getDepartmentTypeLit()
    this.getDepartmentTree()
  },
  methods: {
    handleCurrentChange(newpage){
        this.queryInfo.pagenum=newpage
        this.getDepartmentTree()
    },
    handleSizeChange(newsize){
      this.queryInfo.pagesize=newsize
      this.getDepartmentTree()
    },
    handlechange(){
      if (this.selectedCateKeys.length==2){
        this.selectedCateKeys=[]
        this.$message.warning('警告 只能选择一级部门')
      }
    },
    async getDepartmentTree(){
        var res = await getDepartment(this.queryInfo)
        this.total=res.count
        console.log(res.data,'tree')
        this.cateList=res.data
    },
    // getTagInfo(type) {
    //   let [tag] = this.departmentTypeOptions.filter(
    //     (item) => item.value == type
    //   )
    //   return tag
    // },
    // async getDepartmentTypeLit() {
    //   const result = await getDepartmentType()
    //   if (result.length) {
    //     result.forEach((item) => {
    //       this.departmentTypeOptions.push({
    //         value: item.id,
    //         label: item.name,
    //       })
    //     })
    //   }
    //   this.getDepartmentList()
    // },
 
  
    // 添加部门
    addDepartment() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 可以发起添加部门的网络请求
        // console.log(this.addForm)
        var params ={}
        if (this.selectedCateKeys.length==0){ 
          params.name=this.addForm.name
          params.pid=NaN
        }
        if (this.selectedCateKeys.length==1){
          params.name=this.addForm.name
          params.pid=this.selectedCateKeys[0]
        }
        console.log(params)
          const result = await addDepartment(params)
          console.log(result,'result')
          if (result.code==200) {
            this.addDialogClosed()
            this.$message.success('添加部门成功！')
            // this.getDepartmentList()
            this.getDepartmentTree()
        }
      })
    },

    // 展示编辑部门的对话框
    async showEditDialog(id) {
      const result = await getDepartmentItem(id)
      if (result) {
        this.editForm = result
        this.editDialogVisible = true
      }
    },

    // 修改部门信息并提交
    editDepartment() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改部门信息的数据请求
        const result = await editDepartmentItem(this.editForm)

        if (result) {
          // 关闭对话框
          this.editDialogVisible = false
          // 刷新数据列表
          // this.getDepartmentList()
          this.getDepartmentTree()
          // 提示修改成功
          this.$message.success('更新部门信息成功！')
        }
      })
    },
    // 根据Id删除对应的部门信息
    async removeDepartById(id) {
      // 弹框询问部门是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该部门, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      // 如果部门确认删除，则返回值为字符串 confirm
      // 如果部门取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      removeDepartment(id).then((value) => {
        this.$message.success('删除部门成功！')
        // this.getDepartmentList()
        this.getDepartmentTree()
      })
    },
  },
}
</script>

<style lang="less" scoped>
</style>
